<template>
  <div class="app-install-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h3>应用安装</h3>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="left-section">
        <h3>设备列表</h3>
        <div class="device-summary">
          <span class="summary-text">
            已选择 {{ selectedDevices.length }} 台设备
          </span>
        </div>
      </div>

      <div class="right-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索设备编号..."
          clearable
          class="search-input"
          @input="handleSearch"
        >
          <template #prefix>
            <SvgIcon name="search" size="16px" />
          </template>
        </el-input>

        <el-button-group class="filter-buttons">
          <el-button
            :type="deviceFilter === 'all' ? 'primary' : 'default'"
            @click="setDeviceFilter('all')"
          >
            全部
          </el-button>
          <el-button
            :type="deviceFilter === 'idle' ? 'success' : 'default'"
            @click="setDeviceFilter('idle')"
          >
            空闲
          </el-button>
          <el-button
            :type="deviceFilter === 'busy' ? 'warning' : 'default'"
            @click="setDeviceFilter('busy')"
          >
            忙碌
          </el-button>
        </el-button-group>

        <el-button type="primary" size="default" @click="refreshDevices">
          <SvgIcon name="reload" size="18px" />
          <span style="margin-left: 6px">刷新</span>
        </el-button>
      </div>
    </div>

    <!-- 设备统计 -->
    <div class="device-stats">
      <span class="stat-item">
        空闲:
        <span class="stat-number idle">{{ deviceStats.idle }}</span>
      </span>
      <span class="stat-item">
        忙碌:
        <span class="stat-number busy">{{ deviceStats.busy }}</span>
      </span>
      <span class="stat-item">
        总数:
        <span class="stat-number total">{{ deviceStats.total }}</span>
      </span>

      <div class="selected-info" v-if="selectedDevices.length > 0">
        <el-button
          type="success"
          size="small"
          @click="showInstallPanel = true"
          :disabled="!selectedApk || isAnyOperationInProgress"
          :loading="isAnyOperationInProgress"
        >
          继续选择APK进行安装 ({{ selectedDevices.length }})
        </el-button>
      </div>
    </div>

    <!-- 设备列表 -->

    <div class="device-grid" v-loading="devicesLoading">
      <el-tooltip
        v-for="device in filteredDevices"
        :key="device.device_id"
        :content="getDeviceTooltipContent(device)"
        placement="top"
        :disabled="!shouldShowDeviceTooltip(device)"
        :show-after="500"
        :hide-after="200"
      >
        <div
          class="device-card"
          :class="{
            'device-busy': !isDeviceSelectable(device),
            'device-selected': selectedDevices.includes(device.device_id),
          }"
          @click="toggleDevice(device.device_id, !isDeviceSelectable(device))"
        >
          <div
            class="device-icon"
            @click.stop="navigateToDeviceDetail(device, device.device_id)"
            title="打开设备控制"
          >
            <img
              src="@/assets/images/devices/device-icon.png"
              alt="设备图标"
              class="device-icon-image"
            />
          </div>
          <div class="device-info">
            <div class="device-name">{{ device.device_id || '未知设备' }}</div>
            <div class="device-model">
              型号: {{ device.model || 'undefined' }}
            </div>
          </div>
          <div class="device-status">
            <el-tag :type="getDeviceStatusType(device)" size="small">
              {{ getDeviceStatusText(device) }}
            </el-tag>
            <!-- 任务应用简称显示 -->
            <div
              v-if="
                device.is_busy &&
                device.task_description &&
                getAppShortNameFromTask(device.task_description)
              "
              class="device-task-app"
            >
              {{ getAppShortNameFromTask(device.task_description) }}
            </div>
          </div>
        </div>
      </el-tooltip>

      <div
        v-if="filteredDevices.length === 0 && !devicesLoading"
        class="empty-state"
      >
        <div class="empty-text">暂无设备</div>
      </div>
    </div>

    <!-- 设备分页 -->
    <div class="pagination-section">
      <div class="pagination-wrapper">
        <div class="page-size-selector">
          <span class="page-size-label">每页显示</span>
          <el-select
            v-model="pageSize"
            @change="handleSizeChange"
            size="default"
            style="width: 80px; margin: 0 8px"
          >
            <el-option
              v-for="size in [10, 20, 50, 100]"
              :key="size"
              :label="size"
              :value="size"
            />
          </el-select>
          <span class="page-size-label">条</span>
        </div>

        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :small="false"
          :disabled="false"
          :background="true"
          layout="prev, pager, next, jumper"
          :total="filteredDevicesAll.length"
          :pager-count="7"
          :hide-on-single-page="false"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- APK上传区域 -->
    <div class="upload-area">
      <el-upload
        ref="uploadRef"
        class="upload-dragger"
        drag
        :action="uploadUrl"
        :headers="uploadHeaders"
        :before-upload="beforeUpload"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :show-file-list="false"
        accept=".apk"
        :loading="uploading"
      >
        <div class="upload-content">
          <div class="upload-text">点击上传或拖拽APK文件到此处</div>
          <div class="upload-hint">支持 .apk 格式文件，大小不超过500MB</div>
        </div>
      </el-upload>
    </div>

    <!-- APK文件库工具栏 -->
    <div class="apk-toolbar" v-if="apkList.length > 0 || apkListLoading">
      <div class="apk-left-section">
        <h3>APK文件</h3>
      </div>

      <div class="apk-right-section">
        <el-input
          v-model="apkSearchKeyword"
          placeholder="搜索APK文件名..."
          clearable
          class="apk-search-input"
          @input="handleApkSearch"
        >
          <template #prefix>
            <SvgIcon name="search" size="16px" />
          </template>
        </el-input>

        <el-button-group class="apk-filter-buttons">
          <el-button
            :type="apkFilter === 'all' ? 'primary' : 'default'"
            size="default"
            @click="setApkFilter('all')"
          >
            全部
          </el-button>
          <el-button
            :type="apkFilter === 'litmatch' ? 'success' : 'default'"
            size="default"
            @click="setApkFilter('litmatch')"
          >
            Litmatch
          </el-button>
          <el-button
            :type="apkFilter === 'ofo' ? 'success' : 'default'"
            size="default"
            @click="setApkFilter('ofo')"
          >
            Ofo
          </el-button>
          <el-button
            :type="apkFilter === 'inparty' ? 'success' : 'default'"
            size="default"
            @click="setApkFilter('inparty')"
          >
            InParty
          </el-button>
          <el-button
            :type="apkFilter === 'deer' ? 'success' : 'default'"
            size="default"
            @click="setApkFilter('deer')"
          >
            Deer
          </el-button>
          <el-button
            :type="apkFilter === 'nimi' ? 'success' : 'default'"
            size="default"
            @click="setApkFilter('nimi')"
          >
            NIMI
          </el-button>
          <el-button
            :type="apkFilter === 'other' ? 'warning' : 'default'"
            size="default"
            @click="setApkFilter('other')"
          >
            其他
          </el-button>
        </el-button-group>

        <el-button type="primary" size="default" @click="refreshApkList">
          <SvgIcon name="reload" size="18px" />
          <span style="margin-left: 6px">刷新</span>
        </el-button>
      </div>
    </div>

    <!-- APK文件列表 -->
    <div
      class="apk-cards-grid"
      v-if="apkList.length > 0"
      v-loading="apkListLoading"
    >
      <el-tooltip
        :content="apk.name || '未知文件'"
        placement="top"
        :disabled="!apk.name || apk.name.length <= 20"
        v-for="apk in filteredApkList"
        :key="apk.path"
      >
        <div
          class="apk-card"
          :class="{ 'apk-selected': selectedApk === apk.path }"
          @click="selectApk(apk.path)"
        >
          <div class="apk-card-icon">
            <img
              v-if="getApkIconImage(apk.package || apk.name)"
              :src="getApkIconImage(apk.package || apk.name)"
              :alt="apk.name"
              class="apk-icon-image"
            />
            <SvgIcon v-else name="file" size="24px" />
          </div>
          <div class="apk-card-info">
            <div class="apk-card-name">{{ apk.name || '未知文件' }}</div>
            <div class="apk-card-size">
              {{ apk.size || formatFileSize(apk.size_bytes || 0) }}
            </div>
            <div class="apk-card-time" v-if="apk.package">
              {{ apk.package }}
            </div>
          </div>
          <div class="apk-card-actions">
            <el-tag v-if="selectedApk === apk.path" type="success" size="small">
              已选择
            </el-tag>
          </div>
        </div>
      </el-tooltip>
    </div>

    <!-- APK文件加载状态 -->
    <div
      v-else-if="apkListLoading"
      class="apk-cards-grid"
      v-loading="apkListLoading"
      style="min-height: 128px"
    ></div>

    <!-- 空状态提示 -->
    <div
      v-else-if="!apkListLoading && apkList.length === 0"
      class="apk-empty-hint"
    >
      <SvgIcon name="file" size="20px" />
      <span>暂无APK文件，请先上传</span>
    </div>
    <!-- APK分页 -->
    <div class="pagination-section">
      <div class="pagination-wrapper">
        <div class="page-size-selector">
          <span class="page-size-label">每页显示</span>
          <el-select
            v-model="apkPageSize"
            @change="handleApkSizeChange"
            size="default"
            style="width: 80px; margin: 0 8px"
          >
            <el-option
              v-for="size in [5, 10, 20, 50]"
              :key="size"
              :label="size"
              :value="size"
            />
          </el-select>
          <span class="page-size-label">条</span>
        </div>

        <el-pagination
          v-model:current-page="apkCurrentPage"
          :page-size="apkPageSize"
          :small="false"
          :disabled="false"
          :background="true"
          layout="prev, pager, next, jumper"
          :total="filteredApkListAll.length"
          :pager-count="7"
          :hide-on-single-page="false"
          @current-change="handleApkPageChange"
        />
      </div>
    </div>
    <!-- APK安装按钮区域 -->
    <div class="apk-install-actions" v-if="apkList.length > 0">
      <el-button
        type="primary"
        size="default"
        :disabled="!canQuickInstall"
        :loading="installing"
        @click="handleQuickInstall"
        class="apk-install-button"
      >
        <span style="margin-left: 6px">
          {{ installing ? '正在安装...' : '安装APK' }}
        </span>
      </el-button>
    </div>

    <!-- APK安装面板 -->
    <el-drawer
      v-model="showInstallPanel"
      title="APK安装"
      size="50%"
      direction="rtl"
    >
      <div class="install-panel">
        <div class="selected-devices">
          <h3>选择的设备 ({{ selectedDevices.length }})</h3>
          <div class="device-list">
            <div
              v-for="deviceId in selectedDevices"
              :key="deviceId"
              class="device-item"
            >
              <img
                src="@/assets/images/devices/device-icon.png"
                alt="设备图标"
                class="device-item-icon"
              />
              <span>{{ deviceId }}</span>
            </div>
          </div>
        </div>

        <div class="apk-selection">
          <h3>选择APK文件</h3>
          <div class="apk-list">
            <el-tooltip
              :content="apk.name || '未知文件'"
              placement="top"
              :disabled="!apk.name || apk.name.length <= 25"
              v-for="apk in apkList"
              :key="apk.path"
            >
              <div
                class="apk-item"
                :class="{ selected: selectedApk === apk.path }"
                @click="selectApk(apk.path)"
              >
                <div class="apk-icon">
                  <img
                    v-if="getApkIconImage(apk.package || apk.name)"
                    :src="getApkIconImage(apk.package || apk.name)"
                    :alt="apk.name"
                    class="apk-icon-image"
                  />
                  <SvgIcon v-else name="file" size="24px" />
                </div>
                <div class="apk-info">
                  <div class="apk-name">{{ apk.name || '未知文件' }}</div>
                  <div class="apk-package" v-if="apk.package">
                    <el-tag size="small" type="info">{{ apk.package }}</el-tag>
                  </div>
                  <div class="apk-size">
                    {{ apk.size || formatFileSize(apk.size_bytes || 0) }}
                  </div>
                </div>
              </div>
            </el-tooltip>
          </div>
        </div>

        <div class="install-actions">
          <div
            class="install-tips"
            v-if="selectedDevices.length > 0 && selectedApk"
          >
            <el-alert
              :title="`将安装到 ${selectedDevices.length} 台设备，最大等待时间60秒`"
              type="info"
              :closable="false"
              show-icon
              class="install-alert"
            />
          </div>

          <el-button
            type="primary"
            size="large"
            :disabled="!canInstall"
            :loading="installing"
            @click="handleInstall"
          >
            {{
              installing
                ? '正在安装，请稍候...'
                : `开始批量安装到 ${selectedDevices.length} 台设备`
            }}
          </el-button>

          <div
            class="operation-status"
            v-if="isAnyOperationInProgress && !installing"
          >
            <el-alert
              title="有其他操作正在进行中，请等待完成"
              type="warning"
              :closable="false"
              show-icon
              class="status-alert"
            />
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 安装进度弹窗 -->
    <el-dialog
      v-model="showInstallDialog"
      title="安装进度"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="install-progress">
        <div class="progress-summary">
          <el-progress
            :percentage="installProgress"
            :status="installStatus"
            :stroke-width="8"
          />
          <div class="progress-text">
            {{ installProgressText }}
          </div>
        </div>

        <div class="device-progress-list">
          <div
            v-for="result in installResults"
            :key="result.deviceId"
            class="device-progress-item"
          >
            <div class="device-name">{{ getDeviceName(result.deviceId) }}</div>
            <div class="device-status">
              <el-tag
                :type="result.status === 'success' ? 'success' : 'danger'"
                size="small"
              >
                {{ result.status === 'success' ? '安装成功' : '安装失败' }}
              </el-tag>
              <span class="install-time" v-if="result.installTime">
                {{ result.installTime.toFixed(1) }}s
              </span>
            </div>
            <div v-if="result.message" class="result-message">
              {{ result.message }}
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="closeInstallDialog" :disabled="installing">
          {{ installing ? '安装中...' : '关闭' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 设备控制弹窗 -->
    <!-- <div class="device-control-modal" v-if="showDeviceControlModal">
      <div class="modal-overlay" @click="closeDeviceControlModal"></div>
      <div class="modal-container">
        <div class="modal-header">
          <h3>设备控制 - {{ currentDeviceName }}</h3>
          <div class="header-actions">
            <button
              class="refresh-btn-modal"
              @click="refreshIframe"
              title="刷新"
            >
              刷新
            </button>
            <span
              class="close-btn"
              @click="closeDeviceControlModal"
              title="关闭"
            >
              &times;
            </span>
          </div>
        </div>
        <div class="modal-body">
          <iframe
            :src="currentDeviceUrl"
            frameborder="0"
            class="device-control-frame"
            ref="deviceControlFrame"
          ></iframe>
        </div>
      </div>
    </div> -->
  </div>
  <el-dialog
    v-for="device in filteredDevices"
    :key="device.device_id"
    v-model="dialogStates[device.device_id]"
    draggable
    center
    :modal="false"
    :close-on-click-modal="false"
    style="pointer-events: auto"
    :id="device.device_id"
    :destroy-on-close="true"
    @close="closeDeviceControlModal(device.device_id)"
    :show-close="false"
    :fullscreen="false"
    :width="kuan"
    :style="{
      height: chang + 'px',
      marginTop: '10px',
      zIndex: 2000 + first_z_index,
    }"
    class="device-control-dialog"
    @open="handleDialogOpen"
    @click="handleDialogclick(device.device_id)"
  >
    <template #header="{ titleId, titleClass }">
      <div>
        <h4 :id="titleId" :class="titleClass">设备：{{ device.device_id }}</h4>
      </div>
    </template>
    <div class="modal-header" style="margin-top: 10px">
      <!-- <h3>设备：{{ device.device_id }}</h3> -->
      <div class="header-actions">
        <el-button
          type="primary"
          size="default"
          @click="refreshIframe(device.device_id)"
        >
          刷新
        </el-button>
        <el-button
          type="primary"
          size="default"
          @click="hengPing(device.device_id)"
        >
          {{ hengPingText }}
        </el-button>
      </div>
      <el-button
        type="danger"
        size="small"
        @click="closeDeviceControlModal(device.device_id)"
      >
        <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
      </el-button>
    </div>

    <iframe
      :src="deviceControlFrames[device.device_id]"
      frameborder="0"
      class="device-control-frame"
      :ref="(el) => setIframeRef(el, device.device_id)"
      :style="{ width: kuan - 20 + 'px' }"
    ></iframe>
  </el-dialog>
</template>

<script>
export default {
  name: 'AppInstallV2',
}
</script>

<script  setup>
import { ref, computed, onMounted, nextTick, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import SvgIcon from '@/views/components/SvgIcon.vue'
import emmit from '@/utils/emitter'
let kuan = ref(450)
let chang = ref(815)
let hengPingStatus = ref(false)
let hengPingText = ref('横屏')
const hengPing = (device_id) => {
  hengPingStatus.value = !hengPingStatus.value
  if (hengPingStatus.value) {
    kuan.value = 860
    hengPingText.value = '竖屏'
  } else {
    kuan.value = 450
    hengPingText.value = '横屏'
  }
  refreshIframe(device_id)
}
const dialogStates = reactive({})
const deviceControlFrames = reactive({})
// 响应式数据
const devicesLoading = ref(false)
const apkListLoading = ref(false)
const uploading = ref(false)
const installing = ref(false)
const showInstallDialog = ref(false)
const showInstallPanel = ref(false)

// 设备控制相关数据
const showDeviceControlModal = ref(false)
const currentDeviceName = ref('')
const currentDeviceUrl = ref('')
const deviceControlFrame = ref(null)

const availableDevices = ref([])
const selectedDevices = ref([])
const apkList = ref([])
const selectedApk = ref('')
const installResults = ref([])
const installProgress = ref(0)
const installStatus = ref('')

// 搜索和筛选功能
const searchKeyword = ref('')
const deviceFilter = ref('all')

// APK搜索和筛选功能
const apkSearchKeyword = ref('')
const apkFilter = ref('all')

// APK分页功能
const apkCurrentPage = ref(1)
const apkPageSize = ref(10)

// 分页功能（设备）
const currentPage = ref(1)
const pageSize = ref(20)

// 上传相关
const uploadRef = ref(null)
const uploadUrl = `${import.meta.env.VITE_APP_BASE_API}/devices/apk/upload`
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${localStorage.getItem('access_token')}`,
}))

// 计算属性
const selectedApkName = computed(() => {
  const apk = apkList.value.find((item) => item.path === selectedApk.value)
  return apk ? apk.name : ''
})

const canInstall = computed(() => {
  return (
    selectedDevices.value.length > 0 &&
    selectedApk.value &&
    !installing.value &&
    !devicesLoading.value &&
    !apkListLoading.value
  )
})

// 快速安装：检查是否有选中的设备和APK文件
const canQuickInstall = computed(() => {
  return (
    selectedDevices.value.length > 0 &&
    selectedApk.value &&
    !installing.value &&
    !devicesLoading.value &&
    !apkListLoading.value
  )
})

// 计算是否有任何操作正在进行
const isAnyOperationInProgress = computed(() => {
  return (
    installing.value ||
    devicesLoading.value ||
    apkListLoading.value ||
    uploading.value
  )
})

const installProgressText = computed(() => {
  if (installing.value) {
    return `正在批量安装到 ${selectedDevices.value.length} 台设备，请耐心等待...`
  }
  if (installResults.value.length > 0) {
    const successCount = installResults.value.filter(
      (r) => r.status === 'success',
    ).length
    const totalCount = installResults.value.length
    const failedCount = totalCount - successCount
    if (failedCount === 0) {
      return `🎉 安装完成: 全部 ${totalCount} 台设备安装成功!`
    } else {
      return `⚠️ 安装完成: ${successCount}/${totalCount} 成功，${failedCount} 台失败`
    }
  }
  return ''
})

// 筛选设备（无分页）
const filteredDevicesAll = computed(() => {
  let devices = availableDevices.value

  // 搜索过滤
  if (searchKeyword.value) {
    devices = devices.filter(
      (device) =>
        device.device_id &&
        device.device_id
          .toLowerCase()
          .includes(searchKeyword.value.toLowerCase()),
    )
  }

  // 状态过滤
  if (deviceFilter.value !== 'all') {
    devices = devices.filter((device) => {
      if (deviceFilter.value === 'idle') {
        return isDeviceSelectable(device)
      } else if (deviceFilter.value === 'busy') {
        return (
          device.is_busy &&
          (device.task_type === 'testing' || device.task_type === 'installing')
        )
      }
      return true
    })
  }

  return devices
})

// 分页后的设备
const filteredDevices = computed(() => {
  const devices = filteredDevicesAll.value
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return devices.slice(start, end)
})

// 设备统计（基于筛选后的全部设备）
const deviceStats = computed(() => {
  const devices = filteredDevicesAll.value
  const idle = devices.filter((device) => isDeviceSelectable(device)).length
  const busy = devices.filter(
    (device) =>
      device.is_busy &&
      (device.task_type === 'testing' || device.task_type === 'installing'),
  ).length
  const total = devices.length

  return {
    idle,
    busy,
    total,
  }
})

// 筛选APK列表（无分页）
const filteredApkListAll = computed(() => {
  let apkFiles = apkList.value

  // 搜索过滤
  if (apkSearchKeyword.value) {
    apkFiles = apkFiles.filter(
      (apk) =>
        (apk.name &&
          apk.name
            .toLowerCase()
            .includes(apkSearchKeyword.value.toLowerCase())) ||
        (apk.package &&
          apk.package
            .toLowerCase()
            .includes(apkSearchKeyword.value.toLowerCase())),
    )
  }

  // 筛选过滤
  if (apkFilter.value !== 'all') {
    apkFiles = apkFiles.filter((apk) => {
      const packageName = (apk.package || apk.name || '').toLowerCase()

      switch (apkFilter.value) {
        case 'litmatch':
          return packageName.includes('litmatch')
        case 'ofo':
          return packageName.includes('ofo')
        case 'inparty':
          return packageName.includes('inparty')
        case 'deer':
          return packageName.includes('deer')
        case 'nimi':
          return packageName.includes('nimi')
        case 'other':
          // 其他：不包含上述任何关键词的APK
          return (
            !packageName.includes('litmatch') &&
            !packageName.includes('ofo') &&
            !packageName.includes('inparty') &&
            !packageName.includes('deer') &&
            !packageName.includes('nimi')
          )
        default:
          return true
      }
    })
  }

  return apkFiles
})

// 分页后的APK列表
const filteredApkList = computed(() => {
  const apkFiles = filteredApkListAll.value
  const start = (apkCurrentPage.value - 1) * apkPageSize.value
  const end = start + apkPageSize.value
  return apkFiles.slice(start, end)
})
emmit.on('app_info', (data) => {
  // console.log(data)
  // console.log(data.app_info)
  // console.log(data.app_install)
  // 去重处理：根据device_id去除重复设备
  const devices = data.app_install.devices_info || []
  const uniqueDevices = removeDuplicateDevices(devices)
  availableDevices.value = uniqueDevices
  // // 初始化对话框状态
  // availableDevices.value.forEach((device) => {
  //   dialogStates[device.device_id] = false
  // })
})
// 方法
const refreshDevices = async () => {
  try {
    devicesLoading.value = true
    const response = await request.get('/devices/info?use_blacklist=false')
    if (response.success) {
      // 去重处理：根据device_id去除重复设备
      const devices = response.data.devices_info || []
      const uniqueDevices = removeDuplicateDevices(devices)
      availableDevices.value = uniqueDevices
      // 初始化对话框状态
      uniqueDevices.forEach((device) => {
        dialogStates[device.device_id] = false
      })
      // 如果发现重复数据，在控制台输出警告
      if (devices.length !== uniqueDevices.length) {
        console.warn(
          `检测到重复设备数据，原始数量: ${devices.length}，去重后数量: ${uniqueDevices.length}`,
        )
        ElMessage.warning(
          `检测到 ${
            devices.length - uniqueDevices.length
          } 个重复设备，已自动去重`,
        )
      }
    } else {
      ElMessage.error('获取设备列表失败')
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)

    // 根据错误类型显示不同的错误信息
    let errorMessage = '获取设备列表失败'
    if (error.message && error.message.includes('timeout')) {
      errorMessage = '获取设备列表超时，请检查网络连接'
    } else if (error.response && error.response.status === 401) {
      errorMessage = '登录已过期，请重新登录'
    } else if (error.message) {
      errorMessage = `获取设备列表失败: ${error.message}`
    }

    ElMessage.error({
      message: errorMessage,
      duration: 5000,
    })
  } finally {
    devicesLoading.value = false
  }
}

const refreshApkList = async () => {
  try {
    apkListLoading.value = true
    const response = await request.get('/devices/apk/list')
    if (response.success) {
      apkList.value = response.data.apk_files || []
      // 重置APK分页到第一页
      apkCurrentPage.value = 1
    } else {
      ElMessage.error('获取APK列表失败')
    }
    return response
  } catch (error) {
    console.error('获取APK列表失败:', error)

    // 根据错误类型显示不同的错误信息
    let errorMessage = '获取APK列表失败'
    if (error.message && error.message.includes('timeout')) {
      errorMessage = '获取APK列表超时，请检查网络连接'
    } else if (error.response && error.response.status === 401) {
      errorMessage = '登录已过期，请重新登录'
    } else if (error.message) {
      errorMessage = `获取APK列表失败: ${error.message}`
    }

    ElMessage.error({
      message: errorMessage,
      duration: 5000,
    })
    throw error
  } finally {
    apkListLoading.value = false
  }
}

const handleApkSelection = (value) => {
  console.log('选择APK:', value)
  selectedApk.value = value
}

// 新增的卡片点击处理方法
const toggleDevice = async (deviceId, disabled) => {
  if (disabled) {
    try {
      await ElMessageBox.confirm('是否要停止任务？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      try {
        const res = await request.post(
          `/network/device/${encodeURIComponent(deviceId)}/stop`,
        )
        if (res && (res.success || res.code === 200)) {
          ElMessage.success('已发送停止任务指令')
          await refreshDevices()
        } else {
          ElMessage.error(res?.message || '停止任务失败')
        }
      } catch (e) {
        ElMessage.error('停止任务失败')
      }
    } catch (error) {
      // 用户取消，无需处理
    }
    return
  }

  const index = selectedDevices.value.indexOf(deviceId)
  if (index > -1) {
    selectedDevices.value.splice(index, 1)
  } else {
    selectedDevices.value.push(deviceId)
  }
}

const selectApk = (filePath) => {
  selectedApk.value = filePath
  handleApkSelection(filePath)
}

const beforeUpload = (file) => {
  const isApk = file.name.toLowerCase().endsWith('.apk')
  if (!isApk) {
    ElMessage.error('只能上传APK文件!')
    return false
  }

  const isLt500M = file.size / 1024 / 1024 < 500
  if (!isLt500M) {
    ElMessage.error('文件大小不能超过500MB!')
    return false
  }

  uploading.value = true
  ElMessage.info({
    message: `正在上传 ${file.name}，请稍候...`,
    duration: 0, // 持续显示直到手动关闭
    showClose: false,
  })
  return true
}

const handleUploadSuccess = (response) => {
  uploading.value = false
  // 关闭之前的上传提示
  ElMessage.closeAll()

  if (response.success) {
    ElMessage.success('APK上传成功')
    refreshApkList().then(() => {
      // 自动选择刚上传的APK
      if (response.data) {
        // 兼容不同的响应格式：可能是file_path或path
        const filePath = response.data.file_path || response.data.path
        if (filePath) {
          selectedApk.value = filePath
        } else if (response.data.filename) {
          // 如果没有路径，尝试根据文件名在列表中查找
          const uploadedApk = apkList.value.find(
            (apk) => apk.name === response.data.filename,
          )
          if (uploadedApk) {
            selectedApk.value = uploadedApk.path
          }
        }
      }
    })
  } else {
    ElMessage.error(response.message || 'APK上传失败')
  }
}

const handleUploadError = (error) => {
  uploading.value = false
  // 关闭之前的上传提示
  ElMessage.closeAll()

  console.error('上传失败:', error)
  ElMessage.error('APK上传失败')
}

// 搜索和筛选方法
const handleSearch = () => {
  currentPage.value = 1
}

const setDeviceFilter = (filter) => {
  deviceFilter.value = filter
  currentPage.value = 1
}

// APK搜索和筛选方法
const handleApkSearch = () => {
  apkCurrentPage.value = 1
}

const setApkFilter = (filter) => {
  apkFilter.value = filter
  apkCurrentPage.value = 1
}

// 设备分页方法
const handleCurrentChange = (page) => {
  console.log(`当前页: ${page}`)
  currentPage.value = page
}

const handleSizeChange = (size) => {
  console.log(`每页 ${size} 条`)
  pageSize.value = size
  currentPage.value = 1
}

// APK分页方法
const handleApkPageChange = (page) => {
  console.log(`APK当前页: ${page}`)
  apkCurrentPage.value = page
}

const handleApkSizeChange = (size) => {
  console.log(`APK每页 ${size} 条`)
  apkPageSize.value = size
  apkCurrentPage.value = 1
}

// 立即更新设备状态的方法
const updateDeviceStatus = (
  deviceIds,
  status,
  taskType = null,
  taskDescription = null,
) => {
  if (!Array.isArray(deviceIds)) {
    deviceIds = [deviceIds]
  }

  availableDevices.value = availableDevices.value.map((device) => {
    if (deviceIds.includes(device.device_id)) {
      return {
        ...device,
        is_busy: status === 'idle' ? false : true,
        current_status: status,
        task_type: taskType,
        task_description: taskDescription,
        task_start_time:
          status !== 'idle' ? new Date().toLocaleString('zh-CN') : null,
      }
    }
    return device
  })
}

const handleInstall = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要将 ${selectedApkName.value} 安装到 ${selectedDevices.value.length} 台设备吗？`,
      '确认安装',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    installing.value = true
    showInstallDialog.value = true
    installResults.value = []
    installProgress.value = 0
    installStatus.value = 'active'

    // 立即更新设备状态为安装中
    updateDeviceStatus(
      selectedDevices.value,
      'installing',
      'installing',
      `安装应用: ${selectedApkName.value}`,
    )

    // 显示开始安装的消息
    ElMessage.info({
      message: `开始批量安装，请耐心等待...（超时时间：60秒）`,
      duration: 3000,
    })

    // 调用批量安装接口
    const response = await request.post('/devices/batch-install', {
      device_ids: selectedDevices.value,
      file_path: selectedApk.value,
    })
    console.log(response)
    console.log(response.data)
    installResults.value = response.data.results || []

    // 计算进度
    const successCount = installResults.value.filter(
      (r) => r.status === 'success',
    ).length
    const totalCount = installResults.value.length
    installProgress.value = 100 // 安装完成，进度100%
    installStatus.value = successCount === totalCount ? 'success' : 'exception'

    if (response.success) {
      ElMessage.success({
        message: `安装完成! 成功: ${successCount}/${totalCount}`,
        duration: 5000,
      })
    } else {
      ElMessage.warning({
        message: `安装完成，部分失败。成功: ${successCount}/${totalCount}`,
        duration: 5000,
      })
    }

    // 立即将设备状态重置为空闲
    updateDeviceStatus(selectedDevices.value, 'idle')

    // 刷新设备状态（获取真实状态）
    await refreshDevices()

    // 清空选中的设备和APK
    selectedDevices.value = []
    selectedApk.value = ''

    // 关闭安装面板
    showInstallPanel.value = false
  } catch (error) {
    if (error !== 'cancel') {
      console.error('安装失败:', error)

      // 根据错误类型显示不同的错误信息
      let errorMessage = '安装失败'
      if (error.message && error.message.includes('timeout')) {
        errorMessage = '安装超时，请检查网络连接或稍后重试'
      } else if (error.response && error.response.status === 504) {
        errorMessage = '安装超时，操作可能仍在进行中，请稍后查看设备状态'
      } else if (error.message) {
        errorMessage = `安装失败: ${error.message}`
      }

      ElMessage.error({
        message: errorMessage,
        duration: 5000,
      })
      installStatus.value = 'exception'

      // 安装失败时也要重置设备状态
      updateDeviceStatus(selectedDevices.value, 'idle')

      // 安装失败时也清空选中状态
      selectedDevices.value = []
      selectedApk.value = ''
    }
  } finally {
    installing.value = false
  }
}

// 快速安装方法
const handleQuickInstall = async () => {
  if (!selectedDevices.value.length || !selectedApk.value) {
    ElMessage.warning('请先选择设备和APK文件')
    return
  }

  // 直接调用现有的handleInstall方法
  await handleInstall()
}

const closeInstallDialog = () => {
  showInstallDialog.value = false
  installResults.value = []
  installProgress.value = 0
}

const getDeviceStatusType = (device) => {
  if (device.is_busy) return 'warning'
  return 'success'
}

const getDeviceStatusText = (device) => {
  if (device.is_busy) {
    // 根据任务类型显示更详细的状态
    if (device.task_type === 'testing') return '测试中'
    if (device.task_type === 'installing') return '安装中'
    return '忙碌中'
  }
  return '空闲'
}

const isDeviceSelectable = (device) => {
  // 只有空闲状态的设备才能选择
  return !device.is_busy
}

const shouldShowDeviceTooltip = (device) => {
  // 安装中或测试中状态需要显示气泡
  return (
    device.is_busy &&
    (device.task_type === 'testing' || device.task_type === 'installing')
  )
}

const getDeviceTooltipContent = (device) => {
  if (!shouldShowDeviceTooltip(device)) return ''

  let content = []
  if (device.task_description) {
    content.push(`任务：${device.task_description}`)
  }
  if (device.task_estimated_end_time) {
    content.push(`预计结束：${device.task_estimated_end_time}`)
  }
  return content.join('\n')
}

// 从task_description中提取包名并转换为对应的简称
const getAppShortNameFromTask = (taskDescription) => {
  if (!taskDescription) return ''

  // 包名到简称的映射
  const packageNameMap = {
    'com.litatom.app': 'Lit',
    'com.ofotech.app': 'Ofo',
    'com.ofotech.inparty': 'InParty',
    'com.ofotech.app.in': 'Deer',
    'com.nimispace.app': 'NiMi',
  }

  // 按照包名长度从长到短排序，确保精确匹配
  const sortedPackages = Object.keys(packageNameMap).sort(
    (a, b) => b.length - a.length,
  )

  // 在描述中查找包名
  for (const packageName of sortedPackages) {
    if (taskDescription.includes(packageName)) {
      return packageNameMap[packageName]
    }
  }

  // 如果没有找到匹配的包名，返回空字符串
  return ''
}

const getDeviceName = (deviceId) => {
  const device = availableDevices.value.find((d) => d.device_id === deviceId)
  return device ? device.device_name || device.device_id : deviceId
}

const formatFileSize = (bytes) => {
  // 检查输入是否为有效数值
  if (!bytes || typeof bytes !== 'number' || isNaN(bytes)) {
    return '0 B'
  }
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 去重工具函数：根据device_id去除重复设备
const removeDuplicateDevices = (devices) => {
  if (!Array.isArray(devices)) return []

  const uniqueDevices = []
  const seenIds = new Set()

  for (const device of devices) {
    if (device && device.device_id && !seenIds.has(device.device_id)) {
      seenIds.add(device.device_id)
      uniqueDevices.push(device)
    }
  }

  return uniqueDevices
}

// 手动清理重复数据方法（调试用）
// eslint-disable-next-line no-unused-vars
const cleanDuplicateDevices = () => {
  const originalLength = availableDevices.value.length
  availableDevices.value = removeDuplicateDevices(availableDevices.value)
  const newLength = availableDevices.value.length

  if (originalLength !== newLength) {
    console.warn(`手动清理设备重复数据：${originalLength} -> ${newLength}`)
    ElMessage.warning(`已清理 ${originalLength - newLength} 个重复设备`)
  }
}

// 根据APK包名或文件名获取图标图片
const getApkIconImage = (packageOrFilename) => {
  // 检查输入是否为空
  if (!packageOrFilename || typeof packageOrFilename !== 'string') {
    return null
  }

  const lowerName = packageOrFilename.toLowerCase()

  // 常见应用的图标映射
  const iconMap = {
    litmatch: new URL('@/assets/images/packages/Litmatch.png', import.meta.url)
      .href,
    nimi: new URL('@/assets/images/packages/NIMI.png', import.meta.url).href,
    deer: new URL('@/assets/images/packages/Deer.png', import.meta.url).href,
    inparty: new URL('@/assets/images/packages/InParty.png', import.meta.url)
      .href,
    ofo: new URL('@/assets/images/packages/Ofo.png', import.meta.url).href,
  }

  for (const [key, icon] of Object.entries(iconMap)) {
    if (lowerName.includes(key)) {
      return icon
    }
  }

  return null
}

//新开设备在最上层
let first_z_index = ref(1)
const handleDialogclick = (id) => {
  // dialogStates[id] = false
  // nextTick(() => {
  //   dialogStates[id] = true
  // })
  // first_z_index.value = first_z_index.value + 1
}
const handleDialogOpen = () => {
  first_z_index.value = first_z_index.value + 1
  console.log(first_z_index.value)
}
// 打开设备控制相关方法
const navigateToDeviceDetail = (device, deviceName) => {
  // 使用协议自适应的设备控制配置
  const deviceControlConfig = window.getDeviceControlConfig('auto')

  const encodedUdid = encodeURIComponent(`${deviceName}`)
  const wsUrl = encodeURIComponent(
    `${deviceControlConfig.wsProtocol}://${deviceControlConfig.wsServer}/?action=proxy-adb&remote=tcp%3A8886&udid=${deviceName}`,
  )
  const url = `${deviceControlConfig.baseUrl}#!action=stream&udid=${encodedUdid}&player=mse&ws=${wsUrl}`

  console.log('设备控制URL（协议自适应）:', {
    currentProtocol: window.location.protocol,
    baseUrl: deviceControlConfig.baseUrl,
    wsProtocol: deviceControlConfig.wsProtocol,
    finalUrl: url,
  })

  currentDeviceName.value = deviceName
  // currentDeviceUrl.value = url
  deviceControlFrames[deviceName] = url
  dialogStates[deviceName] = true
  // showDeviceControlModal.value = true
  document.body.style.overflow = 'hidden'
  //elementplus实现dialog遮罩层外的元素可以被操作点击
  nextTick(() => {
    // 把弹窗父亲的父亲 dom 元素添加 pointer-events: none; 防止穿透
    const elDialog = document.getElementById(deviceName)
    // @ts-ignore
    elDialog?.parentNode?.parentNode?.setAttribute(
      'style',
      'pointer-events: none;',
    )
  })
}

const closeDeviceControlModal = (value) => {
  showDeviceControlModal.value = false
  dialogStates[value] = false
  currentDeviceUrl.value = ''
  deviceControlFrames[value] = ''
  document.body.style.overflow = 'auto'
}
// 使用对象存储 refs
const iframeRefs = ref({})

const setIframeRef = (el, id) => {
  iframeRefs.value[id] = el
}
const refreshIframe = (deviceId) => {
  const iframe = iframeRefs.value[deviceId]

  if (iframe) {
    const currentSrc = iframe.src
    iframe.src = ''
    setTimeout(() => {
      iframe.src = currentSrc
      ElMessage.info('正在刷新设备控制页面...')
    }, 50)
  }
}

// 生命周期
onMounted(() => {
  refreshDevices()
  refreshApkList()
})
</script>

<style scoped lang='scss'>
.device-control-dialog .el-dialog__body {
  height: 780px;
}
.device-control-dialog .el-dialog__header {
  height: 10px !important;
  padding: 0 !important;
}
.app-install-container {
  padding: 20px;
  max-width: 100%;
  margin: 0;
  width: 100%;
  // background: #ffffff;
  min-height: calc(100vh - 74px);
}

.page-header {
  margin-bottom: 8px;
}

.page-header h3 {
  margin: 0;
  color: #303133;
  font-size: 22px;
  font-weight: 600;
}

/* 工具栏样式 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  gap: 12px;
}

.left-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.device-summary {
  padding: 2px 8px;
  // background: #f0f7ff;
  border-radius: 4px;
  border: 1px solid var(--el-border-color);
}

.summary-text {
  color: #409eff;
  font-size: 12px;
  font-weight: 500;
}

.search-input {
  width: 300px;
}

.filter-buttons {
  flex-shrink: 0;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

/* 设备统计样式 */
.device-stats {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
  padding: 10px 14px;
  // background: white;
  border-radius: 6px;
  border: 1px solid var(--el-border-color);
  height: 42px;
}

.stat-item {
  color: #606266;
  font-size: 14px;
}

.stat-number {
  font-weight: 600;
  margin-left: 4px;
}

.stat-number.idle {
  color: #67c23a;
}

.stat-number.busy {
  color: #e6a23c;
}

.stat-number.total {
  color: #409eff;
}

.selected-info {
  margin-left: auto;
  height: 32px;
  display: flex;
  align-items: center;
  flex-shrink: 0;
  overflow: hidden;
}

.selected-info .el-button {
  height: 28px;
  line-height: 26px;
  padding: 0 12px;
  font-size: 12px;
}

/* 设备网格样式 */
.device-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 8px;
  margin-bottom: 8px;
  max-height: 264px;
  min-height: 60px;
  overflow-y: auto;
}

.device-card {
  // background: white;
  border: 2px solid var(--el-border-color);
  border-radius: 6px;
  padding: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  min-height: 60px;
  max-width: 280px;
}

.device-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.device-card.device-selected {
  border-color: #409eff;
  // background: #f0f7ff;
}

.device-card.device-busy {
  opacity: 0.6;
  cursor: not-allowed;
  //    background: #f5f5f5;
}

.device-card.device-busy:hover {
  border-color: #e4e7ed;
  box-shadow: none;
}

.device-icon {
  width: 34px;
  height: 34px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
  flex-shrink: 0;
}

.device-icon-image {
  width: 34px;
  height: 34px;
  object-fit: contain;
}

.device-info {
  flex: 1;
  min-width: 0;
  max-width: 150px;
}

.device-name {
  font-weight: 600;
  color: #303133;
  font-size: 13px;
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.2;
}

.device-model {
  color: #909399;
  font-size: 11px;
  margin-bottom: 0;
  line-height: 1.2;
}

.device-status {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.device-status .el-tag {
  font-size: 10px;
  padding: 2px 6px;
  height: auto;
  line-height: 1.2;
}

.device-task-app {
  font-size: 10px;
  color: #409eff;
  font-weight: 600;
  text-align: center;
  padding: 2px 2px;
  // background: #ecf5ff;
  border-radius: 3px;
  border: 1px solid #b3d8ff;
  min-width: 28px;
  box-shadow: 0 1px 2px rgba(64, 158, 255, 0.1);
}

/* 分页样式 */
.pagination-section {
  display: flex;
  justify-content: flex-start;
  margin: 4px 0;
}

/* 上传区域样式 */
.upload-area {
  margin: 4px 0 8px 0;
}

.upload-dragger {
  border: 2px dashed var(--el-border-color);
  border-radius: 6px;
  // background: #fafbfc;
  transition: all 0.3s ease;
}

.upload-dragger:hover {
  border-color: #409eff;
  // background: #f0f7ff;
}

/* 覆盖 Element Plus 的 el-upload-dragger 默认样式 */
.upload-area :deep(.el-upload-dragger) {
  padding: 0 !important;
  border: 2px dashed var(--el-border-color) !important;
  border-radius: 6px !important;
  // background: #fafbfc !important;
  transition: all 0.3s ease !important;
}

.upload-area :deep(.el-upload-dragger):hover {
  border-color: #409eff !important;
  // background: #f0f7ff !important;
}

.upload-content {
  padding: 24px 12px;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 128px;
}

.upload-text {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
  line-height: 1.4;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
  line-height: 1.3;
}

/* APK文件库工具栏样式 */
.apk-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  gap: 8px;
}

.apk-left-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.apk-search-input {
  width: 300px;
}

.apk-filter-buttons {
  flex-shrink: 0;
}

.apk-filter-buttons .el-button {
  font-size: 12px;
  padding: 8px 12px;
}

.apk-right-section {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

/* APK安装按钮区域样式 */
.apk-install-actions {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 12px;
  padding: 8px 12px;
}

.apk-install-button {
  font-size: 14px;
  height: 36px;
  padding: 0 16px;
}

/* 安装面板样式 */
.install-panel {
  padding: 20px;
}

.selected-devices {
  margin-bottom: 24px;
}

.selected-devices h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #303133;
}

.device-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.device-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  // background: #f0f7ff;
  border-radius: 4px;
  border: 1px solid var(--el-border-color);
  color: #409eff;
  font-size: 12px;
}

.device-item-icon {
  width: 20px;
  height: 20px;
  object-fit: contain;
}

.apk-selection {
  margin-bottom: 24px;
}

.apk-selection h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #303133;
}

.apk-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
}

.apk-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-bottom: 1px solid #e4e7ed;
  cursor: pointer;
  transition: background-color 0.3s;
}

.apk-item:last-child {
  border-bottom: none;
}

.apk-item:hover {
  background: #f5f7fa;
}

.apk-item.selected {
  //  background: #f0f7ff;
  border-color: #409eff;
}

.apk-icon {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  // background: #f0f7ff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
  flex-shrink: 0;
}

.apk-icon-image {
  width: 24px;
  height: 24px;
  object-fit: contain;
  border-radius: 4px;
}

.apk-info {
  flex: 1;
  min-width: 0;
}

.apk-name {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.apk-package {
  margin-bottom: 4px;
}

.apk-size {
  color: #909399;
  font-size: 12px;
}

.install-actions {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.install-tips {
  margin-bottom: 16px;
}

.install-alert {
  border-radius: 6px;
  text-align: left;
}

.operation-status {
  margin-top: 16px;
}

.status-alert {
  border-radius: 6px;
  text-align: left;
}

/* 分页样式 */
.pagination-section {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 4px 12px;
  // background: white;
  border-radius: 8px;
  margin-top: 4px;
}

.pagination-wrapper {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 24px;
  width: 100%;
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-size-label {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.page-size-selector :deep(.el-select .el-input__wrapper) {
  border-radius: 6px;
  height: 32px;
}

.pagination-wrapper :deep(.el-pagination) {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-wrapper :deep(.el-pager li) {
  min-width: 32px;
  height: 32px;
  line-height: 30px;
  border-radius: 6px;
  margin: 0 2px;
  font-weight: 500;
  border: 1px solid var(--el-border-color);
  // background: white;
  color: #606266;
}

.pagination-wrapper :deep(.el-pager li:hover) {
  color: #409eff;
  border-color: #409eff;
}

.pagination-wrapper :deep(.el-pager li.is-active) {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination-wrapper :deep(.btn-prev),
.pagination-wrapper :deep(.btn-next) {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  border: 1px solid var(--el-border-color);
  background: white;
  color: #606266;
  font-weight: 500;
}

.pagination-wrapper :deep(.btn-prev:hover),
.pagination-wrapper :deep(.btn-next:hover) {
  color: #409eff;
  border-color: #409eff;
}

.pagination-wrapper :deep(.btn-prev:disabled),
.pagination-wrapper :deep(.btn-next:disabled) {
  color: #c0c4cc;
  // background-color: #fff;
  border-color: #e4e7ed;
  cursor: not-allowed;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .pagination-wrapper {
    flex-direction: column;
    gap: 16px;
  }

  .page-size-selector {
    order: 2;
  }
}

/* 工具栏标题样式 */
.toolbar h3,
.apk-toolbar h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.apk-cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 8px;
  margin-bottom: 8px;
  max-height: 128px;
  overflow-y: auto;
}

.apk-card {
  // background: white;
  border: 2px solid var(--el-border-color);
  border-radius: 6px;
  padding: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  min-height: 60px;
  max-width: 280px;
}

.apk-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.apk-card.apk-selected {
  border-color: #409eff;
  // background: #f0f7ff;
}

.apk-card-icon {
  width: 34px;
  height: 34px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
  flex-shrink: 0;
  //  background: #f8f9fa;
  border-radius: 6px;
}

.apk-icon-image {
  width: 28px;
  height: 28px;
  object-fit: contain;
}

.apk-card-info {
  flex: 1;
  min-width: 0;
  max-width: 150px;
}

.apk-card-name {
  font-weight: 600;
  color: #303133;
  font-size: 13px;
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.2;
}

.apk-card-size {
  color: #909399;
  font-size: 11px;
  margin-bottom: 0;
  line-height: 1.2;
}

.apk-card-time {
  color: #c0c4cc;
  font-size: 10px;
  line-height: 1.2;
}

.apk-card-actions {
  flex-shrink: 0;
}

.apk-card-actions .el-tag {
  font-size: 10px;
  padding: 2px 6px;
  height: auto;
  line-height: 1.2;
}

.apk-empty-hint {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 16px 0;
  padding: 12px 16px;
  // background: #f8f9fa;
  border-radius: 6px;
  color: #909399;
  font-size: 14px;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
  //  background: white;
  border-radius: 6px;
  border: 1px solid var(--el-border-color);
}

.empty-text {
  color: #909399;
  font-size: 14px;
}

/* 安装进度弹窗样式 */
.install-progress {
  padding: 0;
}

.progress-summary {
  margin-bottom: 24px;
}

.progress-text {
  text-align: center;
  margin-top: 8px;
  color: #606266;
}

.device-progress-list {
  max-height: 300px;
  overflow-y: auto;
}

.device-progress-item {
  padding: 12px 0;
  border-bottom: 1px solid #f5f7fa;
}

.device-progress-item:last-child {
  border-bottom: none;
}

.device-progress-item .device-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.device-progress-item .device-status {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.install-time {
  font-size: 12px;
  color: #909399;
}

.result-message {
  font-size: 12px;
  color: #909399;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60px;
  grid-column: 1 / -1;
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-install-container {
    padding: 16px;
  }

  .page-header h3 {
    font-size: 20px;
  }

  .content-grid {
    grid-template-columns: 1fr;
  }

  .device-grid {
    grid-template-columns: 1fr;
    max-height: 264px;
  }

  .apk-cards-grid {
    grid-template-columns: 1fr;
    max-height: 128px;
  }

  .install-section {
    flex-direction: column;
    gap: 16px;
  }

  .install-summary {
    flex-direction: column;
    gap: 8px;
  }

  .toolbar,
  .apk-toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .left-section,
  .apk-left-section {
    flex-direction: column;
    gap: 12px;
    width: 100%;
  }

  .right-section,
  .apk-right-section {
    flex-direction: column;
    gap: 8px;
    width: 100%;
  }

  .search-input,
  .apk-search-input {
    width: 100%;
  }

  .apk-filter-buttons {
    display: flex !important;
    flex-wrap: wrap;
    gap: 4px;
  }

  .apk-filter-buttons .el-button {
    font-size: 10px;
    padding: 4px 8px;
    border-radius: 4px;
    flex: 0 0 auto;
    min-width: 60px;
  }

  .apk-filter-buttons .el-button:first-child {
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
  }

  .apk-filter-buttons .el-button:last-child {
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
  }

  .apk-install-actions {
    justify-content: center;
    padding: 8px;
  }

  .apk-install-button {
    width: 100%;
    max-width: 280px;
  }
}

@media (max-width: 1024px) {
  .device-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }

  .apk-cards-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }

  .apk-filter-buttons .el-button {
    font-size: 11px;
    padding: 6px 10px;
  }
}

@media (max-width: 800px) {
  .app-install-container {
    padding: 12px;
  }

  .device-card,
  .apk-card {
    padding: 6px;
    max-width: none;
  }

  .device-icon,
  .apk-card-icon {
    width: 30px;
    height: 30px;
  }

  .device-icon-image,
  .apk-icon-image {
    width: 26px;
    height: 26px;
  }

  .device-name,
  .apk-card-name {
    font-size: 12px;
  }

  .device-model,
  .apk-card-size {
    font-size: 10px;
  }

  .apk-cards-grid {
    grid-template-columns: 1fr;
  }

  .device-grid {
    grid-template-columns: 1fr;
  }
}

/* 设备控制弹窗样式 */
.device-control-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-container {
  position: relative;
  width: auto;
  max-width: 30%;
  height: 90vh;
  aspect-ratio: 0.486;
  // background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  z-index: 1;
  animation: modal-appear 0.3s ease-out;
  padding: 0;
}

@keyframes modal-appear {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 10px;
  //  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  min-height: 40px;
}

.modal-header h3 {
  margin: 0;
  font-size: 14px;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.refresh-btn-modal {
  display: inline-block;
  padding: 4px 8px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.2s;
}

.refresh-btn-modal:hover {
  background-color: #66b1ff;
}

.close-btn {
  font-size: 24px;
  color: #909399;
  cursor: pointer;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #303133;
}

.modal-body {
  flex: 1;
  overflow: hidden;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 0;
}

.device-control-frame {
  width: 100%;
  height: 100%;
  border: none;
  transform-origin: right center;
}

.device-icon {
  cursor: pointer;
  transition: background-color 0.2s;
}

.device-icon:hover {
  background-color: rgba(64, 158, 255, 0.1);
}

/* 设备控制弹窗响应式样式 */
@media (max-width: 992px) {
  .modal-container {
    max-width: 50%;
    aspect-ratio: 0.486;
  }

  .device-control-frame {
    transform: scale(0.95);
  }
}

@media (max-width: 768px) {
  .modal-container {
    width: auto;
    max-width: 75%;
    height: 85vh;
    aspect-ratio: 0.486;
  }

  .device-control-frame {
    transform: scale(0.9);
  }
}
</style> 